from django.shortcuts import render,redirect
from django.urls import reverse
from django.http import HttpResponse
from django.views import View
from django.conf import settings
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.hashers import check_password
from django.core.paginator import Paginator
from apps.goods.models import GoodsSKU
from apps.order.models import OrderGoods,OrderInfo
from utils.mixin import LoginRequiredMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous.exc import SignatureExpired
from celery_tasks.tasks import *
import re
from .models import *
# Create your views here.

#/user/register
class RegisterView(View):
    """注册"""
    def get(self,request):
        return render(request, "register.html")

    def post(self,request):
        # 接收数据
        username = request.POST['user_name']
        password = request.POST['pwd']
        email = request.POST['email']
        allow = request.POST['allow']

        # 校检数据
        if not all([username, password, email]):
            return render(request, 'register.html', {'errmsg': "数据不完整"})

        # 校检邮箱
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return render(request, 'register.html', {'errmsg': "邮箱格式错误"})

        if allow != 'on':
            return render(request, 'register.html', {'errmsg': "请同意协议"})

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = None

        if user:
            return render(request, 'register.html', {'errmsg': "用户名已存在"})

        user=User.objects.create_user(username, email, password, is_active=False)

        #发送邮箱验证(http:127.0.0.1:8001/user/active/*)
        serizlizer=Serializer(settings.SECRET_KEY,3600)
        token=serizlizer.dumps({'confirm':user.id})
        token=token.decode()
        send_register_active_email(username,email,token)
        #send_register_active_email.delay(username,email,token)

        # 应答
        return redirect(reverse('goods:index'))

#/user/active
class ActiveView(View):
    """激活"""
    def get(self,request,token):
        serizlizer = Serializer(settings.SECRET_KEY, 3600)
        try:
            info = serizlizer.loads(token)
        except SignatureExpired as e:
            #token过期
            return HttpResponse("token过期")

        user=User.objects.get(id=info['confirm'])
        user.is_active=True
        user.save()
        return redirect(reverse('user:login'))

#/user/login
class LoginView(View):
    """登陆"""
    def get(self,request):
        if "username" in request.COOKIES:
            username=request.COOKIES["username"]
            checked="checked"
        else:
            username=""
            checked=""

        return render(request,'login.html',{"username":username,"checked":checked})

    def post(self,request):
        #接收数据
        username=request.POST.get("username")
        password=request.POST.get("pwd")

        #校捡数据
        if not all([username,password]):
            return render(request,"login.html",{"errmsg":"数据不完整"})

        #user=authenticate(username=username,password=password)
        user=User.objects.get(username=username)
        pwd=user.password

        if check_password(password,pwd):
        #if user is not None:
            # the password verified for the user
            if user.is_active:
                #记录登陆态
                login(request,user)
                next_url = request.GET.get("next", reverse("goods:index"))
                respose=redirect(next_url)
                #判断是否记住用户名
                if request.POST["remember"]=="on":
                    respose.set_cookie("username",username,expires=7200)
                else:
                    respose.delete_cookie("username")

                return respose
            else:
                return render(request,"login.html",{"errmsg":"账号未激活"})
        else:
            # the authentication system was unable to verify the username and password
            return render(request, "login.html", {"errmsg": "用户名或密码错误"})

#/user/logout
class LogoutView(View):
    """登出"""
    def get(self,request):
        logout(request)
        return redirect(reverse("goods:index"))

#/user/user
class UserInfoView(LoginRequiredMixin,View):
    """用户中心"""
    def get(self,request):
        # 获取用户信息
        user=request.user
        address = Address.objects.get_default_address(user)

        # 获取前5条浏览记录
        import redis
        r=redis.Redis(host="39.106.207.193",port="6379",db=9)
        history_list=r.lrange("history_key_%d" % user.id,0,4)
        goods_list=[]
        for goods_id in history_list:
            goods=GoodsSKU.objects.get(id=goods_id)
            goods_list.append(goods)

        content={
            "address":address,
            "goods_list":goods_list
        }
        return render(request,"user_center_info.html",content)

#/user/order
class OrderView(LoginRequiredMixin,View):
    """用户订单"""
    def get(self, request,page_num=1):
        orders=OrderInfo.objects.filter(user=request.user)
        for order in orders:
            total=0
            order_goods=OrderGoods.objects.filter(order_id=order.order_id)
            for order_good in order_goods:
                total+=order_good.price*order_good.count
                order_good.amount=order_good.price*order_good.count
            order.order_goods=order_goods
            order.total=total

        p=Paginator(orders,2)
        page_num=int(page_num)
        if page_num>p.num_pages and page_num<1:
            page_num=1
        page=p.page(page_num)

        # 1.总页数小于5页，页面上显示所有页码
        # 2.如果当前页是前3页，显示1-5页
        # 3.如果当前页是后3页，显示后5页
        # 4.其他情况，显示当前页的前2页，当前页，当前页的后2页
        if p.num_pages <= 5:
            pages_btn = range(1, p.num_pages + 1)
        elif page_num <= 3:
            pages_btn = range(1, 6)
        elif p.num_pages - page_num >= 3:
            pages_btn = range(p.num_pages - 4, p.num_pages + 1)
        else:
            pages_btn = range(page_num - 2, page_num + 3)

        content={
            "orders":page,
            "pages_btn":pages_btn
        }
        return render(request, "user_center_order.html",content)

#/user/address
class AddressView(LoginRequiredMixin,View):
    """收获地址"""
    def get(self, request):
        user = request.user
        addr_id=request.GET.get("addr_id")
        if addr_id:
            address = Address.objects.get(id=addr_id)
        else:
            try:
                address=Address.objects.get_default_address(user)
            except Address.DoesNotExist:
                return render(request, "user_center_site.html")
        return render(request, "user_center_site.html",{"address":address})

    def post(self,request):
        #接收数据
        receiver=request.POST.get("receiver")
        addr=request.POST.get("addr")
        zip_code=request.POST.get("zip_code")
        phone=request.POST.get("phone")
        addr_id=request.POST.get("addr_id")

        #校捡数据
        if not all([receiver,addr,phone]):
            return render(request,"user_center_site.html",{"errmsg":"数据不完整"})

        if not re.match(r"^1[3|4|5|7|8]{9}$",phone):
            return render(request,"user_center_site.html",{"errmsg":"手机格式错误"})

        #业务逻辑
        user=request.user
        address=Address.objects.get_default_address(user)

        if addr_id:
            Address.objects.filter(id=addr_id,user=user).update(
                receiver=receiver,
                addr=addr,
                zip_code=zip_code,
                phone=phone,
            )
            # 响应
            return render(request, "user_center_site.html", {"errmsg": "修改成功"})
        else:
            if address:
                #有默认收获地址
                is_default=False
            else:
                # 没有默认收获地址
                is_default=True

            Address.objects.create(
                user=user,
                receiver=receiver,
                addr=addr,
                zip_code=zip_code,
                phone=phone,
                is_default=is_default
            )
            #响应
            return render(request, "user_center_site.html", {"errmsg": "添加成功"})